﻿using System.Linq;
using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
    public class AdminUserRepository : Repository<AdminUser>, IAdminUserRepository
    {
        protected override Expression<Func<AdminUser, int>> PrimaryKeyExpression => r => r.Id;

        public AdminUserRepository(ApiDBContent context) : base(context)
        {
        }

        protected override IEnumerable<AdminUser> IncludeRelationships(IEnumerable<AdminUser> entities, ApiDBContent context)
        {
            DecryptPassword(entities);

            return entities;
        }

        protected override void UpdateEntitiesBeforeCreate(IEnumerable<AdminUser> entities, ApiDBContent context)
        {
            EncryptPassword(entities);
        }

        protected override void UpdateEntitiesBeforeUpdate(IEnumerable<AdminUser> entities, ApiDBContent context)
        {
            EncryptPassword(entities);
        }

        private void EncryptPassword(IEnumerable<AdminUser> entities)
        {
            foreach (var entity in entities)
            {
                entity.Password = PasswordHelper.Rfc2898Encrypt(entity.Password, "daemon");
            }
        }

        private void DecryptPassword(IEnumerable<AdminUser> entities)
        {
            if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, AdminUserRelationshipEnum.Password))
            {
                return;
            }

            foreach (var entity in entities)
            {
                entity.Password = PasswordHelper.Rfc2898Decrypt(entity.Password, "daemon");
            }
        }

        private void GetUserRole(IEnumerable<AdminUser> entities)
        {
            if (RouteParameterHelper.CheckRouteParameter(RelationshipNames, AdminUserRelationshipEnum.UserRole))
            {
                return;
            }

            //var userIds = entities.Select(r => r.Id).ToList();
            //var userRoleIds = Context.UserRole.Where(r => userIds.Contains(r.UserId)).ToList();
            //var userRoleList = Context.AdminRole.Where(r => userRoleIds.Contains(r.Id)).ToList();
            //foreach (AdminUser user in entities)
            //{
            //	var 
            //}
        }
    }
}